home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_perl.idb / usr / freeware / catman / u_man / cat1 / perlobj.Z / perlobj
Encoding:
Text File  |  1998-10-28  |  27.0 KB  |  793 lines

  1.  
  2.  
  3.  
  4.      PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  5.  
  6.  
  7.  
  8.      NNNNAAAAMMMMEEEE
  9.       perlobj - Perl objects
  10.  
  11.      DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.       First    of all,    you need to understand what references are in
  13.       Perl.     See the _p_e_r_l_r_e_f manpage for that.  Second, if you
  14.       still    find the following reference work too complicated, a
  15.       tutorial on object-oriented programming in Perl can be found
  16.       in the _p_e_r_l_t_o_o_t manpage.
  17.  
  18.       If you're still with us, then    here are three very simple
  19.       definitions that you should find reassuring.
  20.  
  21.       1.  An object    is simply a reference that happens to know
  22.           which class it belongs to.
  23.  
  24.       2.  A    class is simply    a package that happens to provide
  25.           methods to deal with object references.
  26.  
  27.       3.  A    method is simply a subroutine that expects an object
  28.           reference    (or a package name, for    class methods) as the
  29.           first argument.
  30.  
  31.       We'll    cover these points now in more depth.
  32.  
  33.       AAAAnnnn OOOObbbbjjjjeeeecccctttt iiiissss SSSSiiiimmmmppppllllyyyy aaaa    RRRReeeeffffeeeerrrreeeennnncccceeee
  34.  
  35.       Unlike say C++, Perl doesn't provide any special syntax for
  36.       constructors.     A constructor is merely a subroutine that
  37.       returns a reference to something "blessed" into a class,
  38.       generally the    class that the subroutine is defined in.  Here
  39.       is a typical constructor:
  40.  
  41.           package Critter;
  42.           sub new {    bless {} }
  43.  
  44.       That word new    isn't special.    You could have written a
  45.       construct this way, too:
  46.  
  47.           package Critter;
  48.           sub spawn    { bless    {} }
  49.  
  50.       In fact, this    might even be preferable, because the C++
  51.       programmers won't be tricked into thinking that new works in
  52.       Perl as it does in C++.  It doesn't.    We recommend that you
  53.       name your constructors whatever makes    sense in the context
  54.       of the problem you're    solving.  For example, constructors in
  55.       the Tk extension to Perl are named after the widgets they
  56.       create.
  57.  
  58.       One thing that's different about Perl    constructors compared
  59.       with those in    C++ is that in Perl, they have to allocate
  60.  
  61.  
  62.  
  63.      Page 1                        (printed 10/23/98)
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.      PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  71.  
  72.  
  73.  
  74.       their    own memory.  (The other    things is that they don't
  75.       automatically    call overridden    base-class constructors.)  The
  76.       {} allocates an anonymous hash containing no key/value
  77.       pairs, and returns it     The _b_l_e_s_s() takes that    reference and
  78.       tells    the object it references that it's now a Critter, and
  79.       returns the reference.  This is for convenience, because the
  80.       referenced object itself knows that it has been blessed, and
  81.       the reference    to it could have been returned directly, like
  82.       this:
  83.  
  84.           sub new {
  85.           my $self = {};
  86.           bless    $self;
  87.           return $self;
  88.           }
  89.  
  90.       In fact, you often see such a    thing in more complicated
  91.       constructors that wish to call methods in the    class as part
  92.       of the construction:
  93.  
  94.           sub new {
  95.           my $self = {};
  96.           bless    $self;
  97.           $self->initialize();
  98.           return $self;
  99.           }
  100.  
  101.       If you care about inheritance    (and you should; see the
  102.       section on _M_o_d_u_l_e_s: _C_r_e_a_t_i_o_n,    _U_s_e, _a_n_d _A_b_u_s_e in the _p_e_r_l_m_o_d
  103.       manpage), then you want to use the two-arg form of bless so
  104.       that your constructors may be    inherited:
  105.  
  106.           sub new {
  107.           my $class = shift;
  108.           my $self = {};
  109.           bless    $self, $class;
  110.           $self->initialize();
  111.           return $self;
  112.           }
  113.  
  114.       Or if    you expect people to call not just CLASS->new()    but
  115.       also $obj->new(), then use something like this.  The
  116.       _i_n_i_t_i_a_l_i_z_e() method used will    be of whatever $class we
  117.       blessed the object into:
  118.  
  119.  
  120.  
  121.  
  122.  
  123.  
  124.  
  125.  
  126.  
  127.  
  128.  
  129.      Page 2                        (printed 10/23/98)
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.      PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  137.  
  138.  
  139.  
  140.           sub new {
  141.           my $this = shift;
  142.           my $class = ref($this) || $this;
  143.           my $self = {};
  144.           bless    $self, $class;
  145.           $self->initialize();
  146.           return $self;
  147.           }
  148.  
  149.       Within the class package, the    methods    will typically deal
  150.       with the reference as    an ordinary reference.    Outside    the
  151.       class    package, the reference is generally treated as an
  152.       opaque value that may    be accessed only through the class's
  153.       methods.
  154.  
  155.       A constructor    may re-bless a referenced object currently
  156.       belonging to another class, but then the new class is
  157.       responsible for all cleanup later.  The previous blessing is
  158.       forgotten, as    an object may belong to    only one class at a
  159.       time.     (Although of course it's free to inherit methods from
  160.       many classes.)  If you find yourself having to do this, the
  161.       parent class is probably misbehaving,    though.
  162.  
  163.       A clarification:  Perl objects are blessed.  References are
  164.       not.    Objects    know which package they    belong to.  References
  165.       do not.  The _b_l_e_s_s() function    uses the reference to find the
  166.       object.  Consider the    following example:
  167.  
  168.           $a = {};
  169.           $b = $a;
  170.           bless $a,    BLAH;
  171.           print "\$b is a ", ref($b), "\n";
  172.  
  173.       This reports $b as being a BLAH, so obviously    _b_l_e_s_s()
  174.       operated on the object and not on the    reference.
  175.  
  176.       AAAA CCCCllllaaaassssssss iiiissss SSSSiiiimmmmppppllllyyyy aaaa PPPPaaaacccckkkkaaaaggggeeee
  177.  
  178.       Unlike say C++, Perl doesn't provide any special syntax for
  179.       class    definitions.  You use a    package    as a class by putting
  180.       method definitions into the class.
  181.  
  182.       There    is a special array within each package called @ISA,
  183.       which    says where else    to look    for a method if    you can't find
  184.       it in    the current package.  This is how Perl implements
  185.       inheritance.    Each element of    the @ISA array is just the
  186.       name of another package that happens to be a class package.
  187.       The classes are searched (depth first) for missing methods
  188.       in the order that they occur in @ISA.     The classes
  189.       accessible through @ISA are known as base classes of the
  190.       current class.
  191.  
  192.  
  193.  
  194.  
  195.      Page 3                        (printed 10/23/98)
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.      PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  203.  
  204.  
  205.  
  206.       All classes implicitly inherit from class UNIVERSAL as their
  207.       last base class.  Several commonly used methods are
  208.       automatically    supplied in the    UNIVERSAL class; see the
  209.       section on _D_e_f_a_u_l_t _U_N_I_V_E_R_S_A_L _m_e_t_h_o_d_s for more    details.
  210.  
  211.       If a missing method is found in one of the base classes, it
  212.       is cached in the current class for efficiency.  Changing
  213.       @ISA or defining new subroutines invalidates the cache and
  214.       causes Perl to do the    lookup again.
  215.  
  216.       If neither the current class,    its named base classes,    nor
  217.       the UNIVERSAL    class contains the requested method, these
  218.       three    places are searched all    over again, this time looking
  219.       for a    method named _A_U_T_O_L_O_A_D().  If an    AUTOLOAD is found,
  220.       this method is called    on behalf of the missing method,
  221.       setting the package global $AUTOLOAD to be the fully
  222.       qualified name of the    method that was    intended to be called.
  223.  
  224.       If none of that works, Perl finally gives up and complains.
  225.  
  226.       Perl classes do method inheritance only.  Data inheritance
  227.       is left up to    the class itself.  By and large, this is not a
  228.       problem in Perl, because most    classes    model the attributes
  229.       of their object using    an anonymous hash, which serves    as its
  230.       own little namespace to be carved up by the various classes
  231.       that might want to do    something with the object.  The    only
  232.       problem with this is that you    can't sure that    you aren't
  233.       using    a piece    of the hash that isn't already used.  A
  234.       reasonable workaround    is to prepend your fieldname in    the
  235.       hash with the    package    name.
  236.  
  237.           sub bump {
  238.           my $self = shift;
  239.           $self->{ __PACKAGE__ . ".count"}++;
  240.           }
  241.  
  242.  
  243.       AAAA MMMMeeeetttthhhhoooodddd iiiissss SSSSiiiimmmmppppllllyyyy aaaa SSSSuuuubbbbrrrroooouuuuttttiiiinnnneeee
  244.  
  245.       Unlike say C++, Perl doesn't provide any special syntax for
  246.       method definition.  (It does provide a little    syntax for
  247.       method invocation though.  More on that later.)  A method
  248.       expects its first argument to    be the object (reference) or
  249.       package (string) it is being invoked on.  There are just two
  250.       types    of methods, which we'll    call class and instance.
  251.       (Sometimes you'll hear these called static and virtual, in
  252.       honor    of the two C++ method types they most closely
  253.       resemble.)
  254.  
  255.       A class method expects a class name as the first argument.
  256.       It provides functionality for    the class as a whole, not for
  257.       any individual object    belonging to the class.     Constructors
  258.  
  259.  
  260.  
  261.      Page 4                        (printed 10/23/98)
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.      PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  269.  
  270.  
  271.  
  272.       are typically    class methods.    Many class methods simply
  273.       ignore their first argument, because they already know what
  274.       package they're in, and don't    care what package they were
  275.       invoked via.    (These aren't necessarily the same, because
  276.       class    methods    follow the inheritance tree just like ordinary
  277.       instance methods.)  Another typical use for class methods is
  278.       to look up an    object by name:
  279.  
  280.           sub find {
  281.           my ($class, $name) = @_;
  282.           $objtable{$name};
  283.           }
  284.  
  285.       An instance method expects an    object reference as its    first
  286.       argument.  Typically it shifts the first argument into a
  287.       "self" or "this" variable, and then uses that    as an ordinary
  288.       reference.
  289.  
  290.           sub display {
  291.           my $self = shift;
  292.           my @keys = @_    ? @_ : sort keys %$self;
  293.           foreach $key (@keys) {
  294.               print "\t$key => $self->{$key}\n";
  295.           }
  296.           }
  297.  
  298.  
  299.       MMMMeeeetttthhhhoooodddd IIIInnnnvvvvooooccccaaaattttiiiioooonnnn
  300.  
  301.       There    are two    ways to    invoke a method, one of    which you're
  302.       already familiar with, and the other of which    will look
  303.       familiar.  Perl 4 already had    an "indirect object" syntax
  304.       that you use when you    say
  305.  
  306.           print STDERR "help!!!\n";
  307.  
  308.       This same syntax can be used to call either class or
  309.       instance methods.  We'll use the two methods defined above,
  310.       the class method to lookup an    object reference and the
  311.       instance method to print out its attributes.
  312.  
  313.           $fred = find Critter "Fred";
  314.           display $fred 'Height', 'Weight';
  315.  
  316.       These    could be combined into one statement by    using a    BLOCK
  317.       in the indirect object slot:
  318.  
  319.           display {find Critter "Fred"} 'Height', 'Weight';
  320.  
  321.       For C++ fans,    there's    also a syntax using -> notation    that
  322.       does exactly the same    thing.    The parentheses    are required
  323.       if there are any arguments.
  324.  
  325.  
  326.  
  327.      Page 5                        (printed 10/23/98)
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334.      PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  335.  
  336.  
  337.  
  338.           $fred = Critter->find("Fred");
  339.           $fred->display('Height', 'Weight');
  340.  
  341.       or in    one statement,
  342.  
  343.           Critter->find("Fred")->display('Height', 'Weight');
  344.  
  345.       There    are times when one syntax is more readable, and    times
  346.       when the other syntax    is more    readable.  The indirect    object
  347.       syntax is less cluttered, but    it has the same    ambiguity as
  348.       ordinary list    operators.  Indirect object method calls are
  349.       parsed using the same    rule as    list operators:    "If it looks
  350.       like a function, it is a function".  (Presuming for the
  351.       moment that you think    two words in a row can look like a
  352.       function name.  C++ programmers seem to think    so with    some
  353.       regularity, especially when the first    word is    "new".)     Thus,
  354.       the parentheses of
  355.  
  356.           new Critter ('Barney', 1.5, 70)
  357.  
  358.       are assumed to surround ALL the arguments of the method
  359.       call,    regardless of what comes after.     Saying
  360.  
  361.           new Critter ('Bam' x 2), 1.4, 45
  362.  
  363.       would    be equivalent to
  364.  
  365.           Critter->new('Bam' x 2), 1.4, 45
  366.  
  367.       which    is unlikely to do what you want.
  368.  
  369.       There    are times when you wish    to specify which class's
  370.       method to use.  In this case,    you can    call your method as an
  371.       ordinary subroutine call, being sure to pass the requisite
  372.       first    argument explicitly:
  373.  
  374.           $fred =  MyCritter::find("Critter", "Fred");
  375.           MyCritter::display($fred,    'Height', 'Weight');
  376.  
  377.       Note however,    that this does not do any inheritance.    If you
  378.       wish merely to specify that Perl should _S_T_A_R_T    looking    for a
  379.       method in a particular package, use an ordinary method call,
  380.       but qualify the method name with the package like this:
  381.  
  382.           $fred = Critter->MyCritter::find("Fred");
  383.           $fred->MyCritter::display('Height', 'Weight');
  384.  
  385.       If you're trying to control where the    method search begins
  386.       _a_n_d you're executing in the class itself, then you may use
  387.       the SUPER pseudo class, which    says to    start looking in your
  388.       base class's @ISA list without having    to name    it explicitly:
  389.  
  390.  
  391.  
  392.  
  393.      Page 6                        (printed 10/23/98)
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.      PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  401.  
  402.  
  403.  
  404.           $self->SUPER::display('Height', 'Weight');
  405.  
  406.       Please note that the SUPER:: construct is meaningful _o_n_l_y
  407.       within the class.
  408.  
  409.       Sometimes you    want to    call a method when you don't know the
  410.       method name ahead of time.  You can use the arrow form,
  411.       replacing the    method name with a simple scalar variable
  412.       containing the method    name:
  413.  
  414.           $method =    $fast ?    "findfirst" : "findbest";
  415.           $fred->$method(@args);
  416.  
  417.  
  418.       DDDDeeeeffffaaaauuuulllltttt UUUUNNNNIIIIVVVVEEEERRRRSSSSAAAALLLL mmmmeeeetttthhhhooooddddssss
  419.  
  420.       The UNIVERSAL    package    automatically contains the following
  421.       methods that are inherited by    all other classes:
  422.  
  423.       isa(CLASS)
  424.           isa returns _t_r_u_e if its object is    blessed    into a
  425.           subclass of CLASS
  426.  
  427.           isa is also exportable and can be    called as a sub    with
  428.           two arguments. This allows the ability to    check what a
  429.           reference    points to. Example
  430.  
  431.           use UNIVERSAL    qw(isa);
  432.  
  433.           if(isa($ref, 'ARRAY')) {
  434.               #...
  435.           }
  436.  
  437.  
  438.       can(METHOD)
  439.           can checks to see    if its object has a method called
  440.           METHOD, if it does then a    reference to the sub is
  441.           returned,    if it does not then _u_n_d_e_f is returned.
  442.  
  443.       VERSION( [NEED] )
  444.           VERSION returns the version number of the    class
  445.           (package).  If the NEED argument is given    then it    will
  446.           check that the current version (as defined by the
  447.           $VERSION variable    in the given package) not less than
  448.           NEED; it will die    if this    is not the case.  This method
  449.           is normally called as a class method.  This method is
  450.           called automatically by the VERSION form of use.
  451.  
  452.           use A    1.2 qw(some imported subs);
  453.           # implies:
  454.           A->VERSION(1.2);
  455.  
  456.  
  457.  
  458.  
  459.      Page 7                        (printed 10/23/98)
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.      PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  467.  
  468.  
  469.  
  470.       NNNNOOOOTTTTEEEE::::    can directly uses Perl's internal code for method
  471.       lookup, and isa uses a very similar method and cache-ing
  472.       strategy. This may cause strange effects if the Perl code
  473.       dynamically changes @ISA in any package.
  474.  
  475.       You may add other methods to the UNIVERSAL class via Perl or
  476.       XS code.  You    do not need to use UNIVERSAL in    order to make
  477.       these    methods    available to your program.  This is necessary
  478.       only if you wish to have isa available as a plain subroutine
  479.       in the current package.
  480.  
  481.       DDDDeeeessssttttrrrruuuuccccttttoooorrrrssss
  482.  
  483.       When the last    reference to an    object goes away, the object
  484.       is automatically destroyed.  (This may even be after you
  485.       exit,    if you've stored references in global variables.)  If
  486.       you want to capture control just before the object is    freed,
  487.       you may define a DESTROY method in your class.  It will
  488.       automatically    be called at the appropriate moment, and you
  489.       can do any extra cleanup you need to do.  Perl passes    a
  490.       reference to the object under    destruction as the first (and
  491.       only)    argument.  Beware that the reference is    a read-only
  492.       value, and cannot be modified    by manipulating    $_[0] within
  493.       the destructor.  The object itself (i.e.  the    thingy the
  494.       reference points to, namely ${$_[0]},    @{$_[0]}, %{$_[0]}
  495.       etc.)    is not similarly constrained.
  496.  
  497.       If you arrange to re-bless the reference before the
  498.       destructor returns, perl will    again call the DESTROY method
  499.       for the re-blessed object after the current one returns.
  500.       This can be used for clean delegation    of object destruction,
  501.       or for ensuring that destructors in the base classes of your
  502.       choosing get called.    Explicitly calling DESTROY is also
  503.       possible, but    is usually never needed.
  504.  
  505.       Do not confuse the foregoing with how    objects    _C_O_N_T_A_I_N_E_D in
  506.       the current one are destroyed.  Such objects will be freed
  507.       and destroyed    automatically when the current object is
  508.       freed, provided no other references to them exist elsewhere.
  509.  
  510.       WWWWAAAARRRRNNNNIIIINNNNGGGG
  511.  
  512.       While    indirect object    syntax may well    be appealing to
  513.       English speakers and to C++ programmers, be not seduced!  It
  514.       suffers from two grave problems.
  515.  
  516.       The first problem is that an indirect    object is limited to a
  517.       name,    a scalar variable, or a    block, because it would    have
  518.       to do    too much lookahead otherwise, just like    any other
  519.       postfix dereference in the language.    (These are the same
  520.       quirky rules as are used for the filehandle slot in
  521.       functions like print and printf.)  This can lead to horribly
  522.  
  523.  
  524.  
  525.      Page 8                        (printed 10/23/98)
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.      PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  533.  
  534.  
  535.  
  536.       confusing precedence problems, as in these next two lines:
  537.  
  538.           move $obj->{FIELD};          # probably wrong!
  539.           move $ary[$i];              # probably wrong!
  540.  
  541.       Those    actually parse as the very surprising:
  542.  
  543.           $obj->move->{FIELD};          # Well, lookee here
  544.           $ary->move->[$i];              # Didn't expect this one, eh?
  545.  
  546.       Rather than what you might have expected:
  547.  
  548.           $obj->{FIELD}->move();          # You    should be so lucky.
  549.           $ary[$i]->move;              # Yeah, sure.
  550.  
  551.       The left side    of ``->'' is not so limited, because it's an
  552.       infix    operator, not a    postfix    operator.
  553.  
  554.       As if    that weren't bad enough, think about this: Perl    must
  555.       guess    _a_t _c_o_m_p_i_l_e _t_i_m_e    whether    name and move above are
  556.       functions or methods.     Usually Perl gets it right, but when
  557.       it doesn't it, you get a function call compiled as a method,
  558.       or vice versa.  This can introduce subtle bugs that are hard
  559.       to unravel.  For example, calling a method new in indirect
  560.       notation--as C++ programmers are so wont to do--can be
  561.       miscompiled into a subroutine    call if    there's    already    a new
  562.       function in scope.  You'd end    up calling the current
  563.       package's new    as a subroutine, rather    than the desired
  564.       class's method.  The compiler    tries to cheat by remembering
  565.       bareword requires, but the grief if it messes    up just    isn't
  566.       worth    the years of debugging it would    likely take you    to to
  567.       track    such subtle bugs down.
  568.  
  569.       The infix arrow notation using ``->''    doesn't    suffer from
  570.       either of these disturbing ambiguities, so we    recommend you
  571.       use it exclusively.
  572.  
  573.       SSSSuuuummmmmmmmaaaarrrryyyy
  574.  
  575.       That's about all there is to it.  Now    you need just to go
  576.       off and buy a    book about object-oriented design methodology,
  577.       and bang your    forehead with it for the next six months or
  578.       so.
  579.  
  580.       TTTTwwwwoooo----PPPPhhhhaaaasssseeeedddd GGGGaaaarrrrbbbbaaaaggggeeee CCCCoooolllllllleeeeccccttttiiiioooonnnn
  581.  
  582.       For most purposes, Perl uses a fast and simple reference-
  583.       based    garbage    collection system.  For    this reason, there's
  584.       an extra dereference going on    at some    level, so if you
  585.       haven't built    your Perl executable using your    C compiler's
  586.       -O flag, performance will suffer.  If    you _h_a_v_e built Perl
  587.       with cc -O, then this    probably won't matter.
  588.  
  589.  
  590.  
  591.      Page 9                        (printed 10/23/98)
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598.      PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  599.  
  600.  
  601.  
  602.       A more serious concern is that unreachable memory with a
  603.       non-zero reference count will    not normally get freed.
  604.       Therefore, this is a bad idea:
  605.  
  606.           {
  607.           my $a;
  608.           $a = \$a;
  609.           }
  610.  
  611.       Even thought $a _s_h_o_u_l_d go away, it can't.  When building
  612.       recursive data structures, you'll have to break the self-
  613.       reference yourself explicitly    if you don't care to leak.
  614.       For example, here's a    self-referential node such as one
  615.       might    use in a sophisticated tree structure:
  616.  
  617.           sub new_node {
  618.           my $self = shift;
  619.           my $class = ref($self) || $self;
  620.           my $node = {};
  621.           $node->{LEFT}    = $node->{RIGHT} = $node;
  622.           $node->{DATA}    = [ @_ ];
  623.           return bless $node =>    $class;
  624.           }
  625.  
  626.       If you create    nodes like that, they (currently) won't    go
  627.       away unless you break    their self reference yourself.    (In
  628.       other    words, this is not to be construed as a    feature, and
  629.       you shouldn't    depend on it.)
  630.  
  631.       Almost.
  632.  
  633.       When an interpreter thread finally shuts down    (usually when
  634.       your program exits), then a rather costly but    complete
  635.       mark-and-sweep style of garbage collection is    performed, and
  636.       everything allocated by that thread gets destroyed.  This is
  637.       essential to support Perl as an embedded or a
  638.       multithreadable language.  For example, this program
  639.       demonstrates Perl's two-phased garbage collection:
  640.  
  641.           #!/usr/bin/perl
  642.           package Subtle;
  643.  
  644.           sub new {
  645.           my $test;
  646.           $test    = \$test;
  647.           warn "CREATING " . \$test;
  648.           return bless \$test;
  649.           }
  650.  
  651.  
  652.  
  653.  
  654.  
  655.  
  656.  
  657.      Page 10                        (printed 10/23/98)
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664.      PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  665.  
  666.  
  667.  
  668.           sub DESTROY {
  669.           my $self = shift;
  670.           warn "DESTROYING $self";
  671.           }
  672.  
  673.           package main;
  674.  
  675.           warn "starting program";
  676.           {
  677.           my $a    = Subtle->new;
  678.           my $b    = Subtle->new;
  679.           $$a =    0;  # break selfref
  680.           warn "leaving    block";
  681.           }
  682.  
  683.           warn "just exited    block";
  684.           warn "time to die...";
  685.           exit;
  686.  
  687.       When run as /_t_m_p/_t_e_s_t, the following output is produced:
  688.  
  689.           starting program at /tmp/test line 18.
  690.           CREATING SCALAR(0x8e5b8) at /tmp/test line 7.
  691.           CREATING SCALAR(0x8e57c) at /tmp/test line 7.
  692.           leaving block at /tmp/test line 23.
  693.           DESTROYING Subtle=SCALAR(0x8e5b8)    at /tmp/test line 13.
  694.           just exited block    at /tmp/test line 26.
  695.           time to die... at    /tmp/test line 27.
  696.           DESTROYING Subtle=SCALAR(0x8e57c)    during global destruction.
  697.  
  698.       Notice that "global destruction" bit there?  That's the
  699.       thread garbage collector reaching the    unreachable.
  700.  
  701.       Objects are always destructed, even when regular refs    aren't
  702.       and in fact are destructed in    a separate pass    before
  703.       ordinary refs    just to    try to prevent object destructors from
  704.       using    refs that have been themselves destructed.  Plain refs
  705.       are only garbage-collected if    the destruct level is greater
  706.       than 0.  You can test    the higher levels of global
  707.       destruction by setting the PERL_DESTRUCT_LEVEL environment
  708.       variable, presuming -DDEBUGGING was enabled during perl
  709.       build    time.
  710.  
  711.       A more complete garbage collection strategy will be
  712.       implemented at a future date.
  713.  
  714.       In the meantime, the best solution is    to create a non-
  715.       recursive container class that holds a pointer to the    self-
  716.       referential data structure.  Define a    DESTROY    method for the
  717.       containing object's class that manually breaks the
  718.       circularities    in the self-referential    structure.
  719.  
  720.  
  721.  
  722.  
  723.      Page 11                        (printed 10/23/98)
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730.      PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  731.  
  732.  
  733.  
  734.      SSSSEEEEEEEE AAAALLLLSSSSOOOO
  735.       A kinder, gentler tutorial on    object-oriented    programming in
  736.       Perl can be found in the _p_e_r_l_t_o_o_t manpage.  You should also
  737.       check    out the    _p_e_r_l_b_o_t    manpage    for other object tricks,
  738.       traps, and tips, as well as the _p_e_r_l_m_o_d_l_i_b manpage for some
  739.       style    guides on constructing both modules and    classes.
  740.  
  741.  
  742.  
  743.  
  744.  
  745.  
  746.  
  747.  
  748.  
  749.  
  750.  
  751.  
  752.  
  753.  
  754.  
  755.  
  756.  
  757.  
  758.  
  759.  
  760.  
  761.  
  762.  
  763.  
  764.  
  765.  
  766.  
  767.  
  768.  
  769.  
  770.  
  771.  
  772.  
  773.  
  774.  
  775.  
  776.  
  777.  
  778.  
  779.  
  780.  
  781.  
  782.  
  783.  
  784.  
  785.  
  786.  
  787.  
  788.  
  789.      Page 12                        (printed 10/23/98)
  790.  
  791.  
  792.  
  793.